from ..model.student_model import Student
from ..configuration.student_configuration import StudentSettings
import asyncmy
from typing import List

class MySQLStudentRepository:
    def __init__(self):
        self.pool = None
        self.settings = StudentSettings()

    async def connect(self):
        """初始化数据库连接池"""
        if not self.pool:
            self.pool = await asyncmy.create_pool(
                host=self.settings.db_host,
                user=self.settings.db_user,
                password=self.settings.db_password,
                db=self.settings.db_name,
                port=self.settings.db_port,
                autocommit=True,
                charset='utf8mb4',
                use_unicode=True
            )

    async def get_all_students(self) -> List[dict]:
        """获取所有学生信息"""
        async with self.pool.acquire() as conn:
            async with conn.cursor() as cur:
                # 设置连接字符集
                await cur.execute("SET NAMES utf8mb4")
                await cur.execute("SELECT id, name, age, major FROM students")
                rows = await cur.fetchall()
                
                # 获取列名
                columns = [desc[0] for desc in cur.description]
                
                # 将结果转换为字典列表，确保字符串正确编码
                result = []
                for row in rows:
                    student_dict = {}
                    for i, col in enumerate(columns):
                        value = row[i]
                        if isinstance(value, str):
                            # 确保字符串使用正确的编码
                            student_dict[col] = value.encode('utf-8').decode('utf-8')
                        else:
                            student_dict[col] = value
                    result.append(student_dict)
                
                return result

    async def close(self):
        """关闭数据库连接池"""
        if self.pool:
            try:
                await self.pool.close()
            except Exception as e:
                print(f"Error closing database pool: {e}")
        self.pool = None
